package metrics

import (
	"strconv"
	"time"

	"github.com/pkg/errors"
)

// TimeFormat +8
const TimeFormat = "2006-01-02 15:04:05"

func TimeNow() string {
	return time.Now().Format(TimeFormat)
}

func TimeNowUnix() string {
	return strconv.FormatInt(time.Now().Unix(), 10)
}

func FormatTime(t time.Time) string {
	return t.Format(TimeFormat)
}

func ParseTimeUnix(timestamp string) (time.Time, error) {

	// 如果时间格式为 值保留到秒即可

	i, err := strconv.ParseInt(timestamp, 10, 64)
	if err != nil {
		return time.Time{}, err
	}
	return time.Unix(i, 0), nil
}

// ParseTimeFromTo
// from, to is time unix string
func ParseTimeFromTo(from, to string) (startTime, endTime time.Time, err error) {
	// 如果开始时间为空则不限制开始时间
	if from == "" {
		//则开始时间 设置为十年前
		startTime = time.Now().Add(-10 * 365 * 24 * time.Hour)
	} else {
		// 解析开始时间
		startTime, err = ParseTimeUnix(from)
		if err != nil {
			err = errors.Errorf("Error parsing start time: %v", err)
			return
		}
	}
	if to == "" {
		//则结束时间 设置为现在
		endTime = time.Now()
	} else {
		// 解析结束时间
		endTime, err = ParseTimeUnix(to)
		if err != nil {
			err = errors.Errorf("Error parsing end time: %v", err)
			return
		}
	}
	// 如果开始时间大于结束时间则返回错误
	if startTime.After(endTime) {
		err = errors.New("Start time must be before end time")
		return
	}
	return
}
